package com.apply.controller;

import com.apply.config.Results;
import com.apply.config.utils.RandomUtil;
import com.apply.config.web.SidAuthContext;
import com.apply.entity.ApplyInfo;
import com.apply.entity.ExamInfo;
import com.apply.entity.SysUser;
import com.apply.service.AuthService;
import com.apply.service.RedisService;
import com.apply.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/private/user/")
@Api(value = "user", tags = "用户")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private AuthService authService;
    @Autowired
    private RedisService redisService;
    @Value("${email.expires}")
    private int expires;

    @ApiOperation(value = "管理员登录验证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysUser", value = "用户信息", dataType = "SysUser")
    })
    @PostMapping("/pub/manageLogin")
    public Results manageLogin(HttpServletResponse response, SysUser sysUser) {

        SysUser login = userService.login(sysUser, 2);
        if (null == login) {
            return Results.error("用户不存在");
        }
        String token = authService.sidAuthToken(login);
        response.setHeader("sid", token);
        return Results.success(token);
    }

    @ApiOperation(value = "登录验证", tags = "user")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysUser", value = "用户信息", dataType = "SysUser")
    })
    @PostMapping("/pub/login")
    public Results login(HttpServletResponse response, SysUser sysUser) {
        SysUser login = userService.login(sysUser, 1);
        if (null == login) {
            return Results.error("用户名或密码错误");
        }
        String token = authService.sidAuthToken(login);
        response.setHeader("sid", token);
        return Results.success(token);
    }

    @ApiOperation(value = "注销当前登录的用户")
    @GetMapping("logout")
    public Results logout(HttpServletRequest request) {
        String sid = request.getHeader("sid");
        Validate.notNull(sid, "当前用户未登录！");
        authService.delete(sid);
        return Results.success();
    }

    @ApiOperation(value = "注册", tags = "user")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysUser", value = "用户信息", dataType = "SysUser"),
            @ApiImplicitParam(name = "validate", value = "验证码", dataType = "string")
    })
    @PostMapping("/pub/regist")
    public Results register(SysUser sysUser, @RequestParam(name = "validate", required = true) String validate) {
        String code = redisService.get(sysUser.getUsername());
        if (StringUtils.isNotEmpty(code) && code.equals(validate)) {
            SysUser newUser = userService.insertUser(sysUser, 1);
            Validate.notNull(newUser, "注册失败,用户已经存在！");
            log.info("注册成功！");
            return Results.success();
        }
        log.info("注册失败,验证码失效！");
        return Results.error("注册失败");
    }

    @ApiOperation(value = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "emailAddress", value = "邮箱地址", dataType = "string"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "string"),
            @ApiImplicitParam(name = "token", value = "验证码", dataType = "string")
    })
    @PostMapping("/pub/updatePassword")
    public Results updatePassword(String emailAddress, String password, String token) {
        String code = redisService.get(emailAddress);
        if (StringUtils.isNotEmpty(code) && code.equals(token)) {
            if (userService.updatePassword(emailAddress, password)) {
                return Results.success();
            }
        }
        return Results.success("修改失败，请重试！");
    }

    @ApiOperation(value = "从Redis里查询当前登录的用户信息")
    @GetMapping("getOne")
    public Results getOne() {
        SysUser sysUserInfo = SidAuthContext.get();
        if (sysUserInfo == null) {
            return Results.error("登录信息已失效，请重新登录");
        }
        return Results.success(sysUserInfo);
    }

    @ApiOperation(value = "发送邮件验证码", tags = "send mail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "邮箱地址", dataType = "string", required = true)
    })
    @PostMapping("/pub/sendEmail")
    public Results sendEmail(HttpSession session, @RequestParam(name = "address", required = true) String address) {
        String random = RandomUtil.getRandom(4, 0, 9);
        userService.sendEmailCode(random, address);
        redisService.set(address, expires, random);
        return Results.success();
    }

    @ApiOperation(value = "根据用户信息分页查询用户信息", notes = "账户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "realname", value = "真实姓名（模糊查询）", dataType = "string"),
            @ApiImplicitParam(name = "username", value = "手机号（模糊查询）", dataType = "string"),
            @ApiImplicitParam(name = "sex", value = "手机号", dataType = "string"),
            @ApiImplicitParam(name = "pageNum", value = "页码(0开始)", required = true)
    })
    @GetMapping("querySysUser")
    public Results querySysUser(SysUser sysUser, @RequestParam(value = "pageNum", required = false, defaultValue = "0") Integer pageNum) {
        return Results.success(userService.querySysUser(sysUser, pageNum));
    }

    @ApiOperation(value = "修改用户信息")
    @PostMapping("updateSysUser")
    public Results updateSysUser(HttpServletRequest request, SysUser sysUser) {
        SysUser user = SidAuthContext.get();
        sysUser.setId(user.getId());
        return Results.success(userService.updateSysUser(sysUser, request.getHeader("sid")));
    }

    @ApiOperation(value = "查询报名信息", notes = "查询报名信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examName", value = "考试名称", dataType = "string"),
            @ApiImplicitParam(name = "pageNum", value = "页码(0开始)", required = true)
    })
    @GetMapping("pageUserApplyInfo")
    public Results querySysUser(String examName,
                                @RequestParam(value = "pageNum", required = false, defaultValue = "0") Integer page,
                                @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        ApplyInfo applyInfo = new ApplyInfo();
        ExamInfo examInfo = new ExamInfo();
        examInfo.setExamName(examName);
        SysUser user = SidAuthContext.get();
        applyInfo.setSysUser(user);
        applyInfo.setExamInfo(examInfo);
        return Results.success(userService.pageUserApplyInfo(applyInfo, new PageRequest(page, pageSize)));
    }
}